#!/bin/bash
source ./00_Base/tools/color_echo.sh

build_path='./build'
out_path='./out/bin'

function clean_build_directory()
{
    if [ -d ${build_path} ]; then
        echo_green "clean $build_path"
        rm -r ${build_path}
    fi
    mkdir ${build_path}
}

function build()
{
    current_pwd=$(pwd)
    if [ ! -d ${build_path} ]; then
        mkdir ${build_path}
    fi
    cd ${build_path}
    cmake .. && make -j40
    cd ${current_pwd}
}

function test() {
    current_pwd=$(pwd)
    cd "$out_path"

    if [ $# -gt 0 ]; then
        local target_file=$1

        if [ ! -x "$target_file" ]; then
            echo "指定的文件不存在或不可执行"
            cd "$current_pwd"
            return 1
        fi

        echo "执行 $target_file ..."
        ./"$target_file"
    else
        # 查找当前目录下的所有可执行文件并将它们存储在数组中
        files=($(find . -type f -executable))

        # 对文件名进行排序（这里需要一个有效的排序方法）
        # 假设 sorted_files 已经被正确排序
        sorted_files=("${files[@]}")

        for file in "${sorted_files[@]}"; do
            echo ""
            echo "执行 $file ..."
            ./"$file"
        done
    fi

    cd "$current_pwd"
}

function test_python()
{
    pytest -s 01_DesignPatterns/01_CreationalDesignPatterns/*/*.py
    pytest -s 01_DesignPatterns/02_StructuralDesignPatterns/*/*.py
    pytest -s 01_DesignPatterns/03_BehavioralDesignPatterns/*/*.py
}

if [ "$1" = "clean" ]; then
    echo_green "#########"
    echo_green "clean ..."
    echo_green "#########"
    clean_build_directory
fi

echo -e "\n"
echo_green "#########"
echo_green "build ..."
echo_green "#########"
build

echo -e "\n"
echo_green "#########"
echo_green "test ..."
echo_green "#########"
test LeetCodeTest

# echo -e "\n"
# echo_green "#########"
# echo_green "test_python ..."
# echo_green "#########"
# test_python